package com.tss.ui;

import com.tss.service.DeviceService;
import com.tss.service.TicketService;
import com.tss.service.impl.DeviceServiceImpl;
import com.tss.service.impl.TicketServiceImpl;
import com.tss.utils.DBUtil;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 主窗口类
 */
public class MainFrame extends JFrame {
    
    // 服务层对象
    private TicketService ticketService;
    private DeviceService deviceService;
    
    // UI组件
    private JTextArea displayArea;                    // 显示屏
    private JPanel destinationKeyboardPanel;          // 目的地键盘面板
    private JPanel ticketTypePanel;                   // 车票键盘面板
    private JPanel controlPanel;                      // 继续/取消键盘面板
    private JPanel paymentPanel;                      // 支付面板
    private JPanel printerPanel;                      // 打印机面板
    private JPanel instructionPanel;                  // 操作说明面板
    
    // 状态变量
    private String destinationCode = "";              // 目的地代码
    private String selectedTicketType = "";           // 选择的车票类型
    private String selectedCategory = "";             // 选择的座席类型
    private double totalAmount = 0.0;                 // 总金额
    private int ticketQuantity = 1;                   // 票数量
    private boolean isDestSelected = false;           // 是否已选择目的地
    private boolean isTicketTypeSelected = false;     // 是否已选择车票类型
    
    /**
     * 构造方法
     */
    public MainFrame() {
        // 初始化服务层对象
        ticketService = new TicketServiceImpl();
        deviceService = new DeviceServiceImpl();
        
        // 初始化数据库
        DBUtil.initDatabase();
        
        // 设置窗口属性
        setTitle("TSS单机售票系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 初始化UI组件
        initComponents();
        
        // 执行设备自检
        boolean ready = deviceService.checkAllStatus();
        if (ready) {
            updateDisplay("系统已就绪，请选择目的地。");
        } else {
            updateDisplay("设备自检失败，请联系管理员。");
        }
    }
    
    /**
     * 初始化UI组件
     */
    private void initComponents() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        setContentPane(mainPanel);
        
        // 左侧面板
        JPanel leftPanel = new JPanel(new BorderLayout(5, 5));
        
        // 操作说明面板
        instructionPanel = createInstructionPanel();
        leftPanel.add(instructionPanel, BorderLayout.NORTH);
        
        // 打印机面板
        printerPanel = createPrinterPanel();
        leftPanel.add(printerPanel, BorderLayout.CENTER);
        
        mainPanel.add(leftPanel, BorderLayout.WEST);
        
        // 中央面板
        JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
        
        // 显示屏面板
        JPanel displayPanel = createDisplayPanel();
        centerPanel.add(displayPanel, BorderLayout.CENTER);
        
        // 支付面板
        paymentPanel = createPaymentPanel();
        centerPanel.add(paymentPanel, BorderLayout.SOUTH);
        
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        
        // 右侧面板
        JPanel rightPanel = new JPanel(new BorderLayout(5, 5));
        
        // 目的地键盘面板
        destinationKeyboardPanel = createDestinationKeyboardPanel();
        
        // 车票键盘面板
        ticketTypePanel = createTicketTypePanel();
        
        // 控制面板
        controlPanel = createControlPanel();
        
        // 添加到右侧面板
        JPanel keyboardPanel = new JPanel(new BorderLayout(5, 5));
        keyboardPanel.add(destinationKeyboardPanel, BorderLayout.NORTH);
        keyboardPanel.add(ticketTypePanel, BorderLayout.CENTER);
        keyboardPanel.add(controlPanel, BorderLayout.SOUTH);
        rightPanel.add(keyboardPanel, BorderLayout.CENTER);
        
        mainPanel.add(rightPanel, BorderLayout.EAST);
    }
    
    /**
     * 创建显示屏面板
     */
    private JPanel createDisplayPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("显示屏"));
        
        displayArea = new JTextArea(10, 30);
        displayArea.setEditable(false);
        displayArea.setLineWrap(true);
        displayArea.setWrapStyleWord(true);
        displayArea.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        
        JScrollPane scrollPane = new JScrollPane(displayArea);
        panel.add(scrollPane, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建操作说明面板
     */
    private JPanel createInstructionPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("一些操作说明"));
        
        JTextArea instructionArea = new JTextArea(5, 15);
        instructionArea.setEditable(false);
        instructionArea.setLineWrap(true);
        instructionArea.setWrapStyleWord(true);
        instructionArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        instructionArea.setText("1. 使用目的地键盘输入目的地代码\n" +
                "2. 使用车票键盘选择车票类型\n" +
                "3. 插入MCard卡或投入现金支付\n" +
                "4. 取票完成交易");
        
        panel.add(new JScrollPane(instructionArea), BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建打印机面板
     */
    private JPanel createPrinterPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("打印机"));
        
        JTextArea printerArea = new JTextArea(8, 15);
        printerArea.setEditable(false);
        printerArea.setBackground(Color.LIGHT_GRAY);
        printerArea.setText("票据将在此打印...");
        
        panel.add(new JScrollPane(printerArea), BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建目的地键盘面板
     */
    private JPanel createDestinationKeyboardPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("目的地键盘"));
        
        // 显示输入的代码
        JTextField codeField = new JTextField();
        codeField.setEditable(false);
        codeField.setFont(new Font("微软雅黑", Font.BOLD, 14));
        codeField.setHorizontalAlignment(JTextField.CENTER);
        panel.add(codeField, BorderLayout.NORTH);
        
        // 数字键盘
        JPanel keyPanel = new JPanel(new GridLayout(4, 3, 5, 5));
        String[] keys = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#"};
        
        for (String key : keys) {
            JButton button = new JButton(key);
            button.setFont(new Font("微软雅黑", Font.BOLD, 14));
            button.addActionListener(e -> {
                if (key.equals("#")) {
                    // 确认输入
                    destinationCode = codeField.getText();
                    if (destinationCode.isEmpty()) {
                        updateDisplay("请输入目的地代码！");
                        return;
                    }
                    
                    boolean valid = ticketService.validateDestination(destinationCode);
                    if (valid) {
                        isDestSelected = true;
                        updateDisplay("目的地代码 " + destinationCode + " 有效。请选择车票类型。");
                    } else {
                        updateDisplay("目的地代码 " + destinationCode + " 无效，请重新输入。");
                        codeField.setText("");
                        destinationCode = "";
                    }
                } else if (key.equals("*")) {
                    // 清除输入
                    codeField.setText("");
                } else {
                    // 添加数字
                    codeField.setText(codeField.getText() + key);
                }
            });
            keyPanel.add(button);
        }
        
        panel.add(keyPanel, BorderLayout.CENTER);
        JLabel instructionLabel = new JLabel("目的地键盘", JLabel.CENTER);
        panel.add(instructionLabel, BorderLayout.SOUTH);
        
        return panel;
    }
    
    /**
     * 创建车票键盘面板
     */
    private JPanel createTicketTypePanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("车票键盘"));
        
        JPanel typePanel = new JPanel(new GridLayout(3, 2, 5, 5));
        
        // 车票类型按钮
        JButton singleBtn = new JButton("单程票");
        singleBtn.addActionListener(e -> selectTicketType("单程票"));
        typePanel.add(singleBtn);
        
        JButton roundBtn = new JButton("往返票");
        roundBtn.addActionListener(e -> selectTicketType("往返票"));
        typePanel.add(roundBtn);
        
        JButton multiBtn = new JButton("多次票");
        multiBtn.addActionListener(e -> selectTicketType("多次票"));
        typePanel.add(multiBtn);
        
        // 座席类型按钮
        JButton normalBtn = new JButton("普通座");
        normalBtn.addActionListener(e -> selectCategory("普通座"));
        typePanel.add(normalBtn);
        
        JButton softBtn = new JButton("软座");
        softBtn.addActionListener(e -> selectCategory("软座"));
        typePanel.add(softBtn);
        
        panel.add(typePanel, BorderLayout.CENTER);
        JLabel instructionLabel = new JLabel("车票键盘", JLabel.CENTER);
        panel.add(instructionLabel, BorderLayout.SOUTH);
        
        return panel;
    }
    
    /**
     * 创建控制面板
     */
    private JPanel createControlPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("继续/取消键盘"));
        
        JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 10, 10));
        
        JButton continueBtn = new JButton("继续");
        continueBtn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        continueBtn.addActionListener(e -> {
            if (isTicketTypeSelected && isDestSelected) {
                updateDisplay("请支付金额：¥" + totalAmount);
            } else {
                updateDisplay("请先选择目的地和车票类型！");
            }
        });
        buttonPanel.add(continueBtn);
        
        JButton cancelBtn = new JButton("取消");
        cancelBtn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelBtn.addActionListener(e -> resetAllSelections());
        buttonPanel.add(cancelBtn);
        
        panel.add(buttonPanel, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建支付面板
     */
    private JPanel createPaymentPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(createTitledBorder("支付方式"));
        
        JPanel paymentBtnPanel = new JPanel(new GridLayout(1, 3, 10, 10));
        
        JButton cardBtn = new JButton("插卡口");
        cardBtn.addActionListener(e -> processPayment("现金卡"));
        paymentBtnPanel.add(cardBtn);
        
        JButton coinBtn = new JButton("硬币口");
        coinBtn.addActionListener(e -> processPayment("硬币"));
        paymentBtnPanel.add(coinBtn);
        
        JButton billBtn = new JButton("纸币槽");
        billBtn.addActionListener(e -> processPayment("纸币"));
        paymentBtnPanel.add(billBtn);
        
        panel.add(paymentBtnPanel, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建带标题的边框
     */
    private Border createTitledBorder(String title) {
        return BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
                title,
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 12)
        );
    }
    
    /**
     * 更新显示屏文本
     */
    private void updateDisplay(String message) {
        displayArea.setText(message);
    }
    
    /**
     * 选择车票类型
     */
    private void selectTicketType(String type) {
        if (!isDestSelected) {
            updateDisplay("请先选择目的地！");
            return;
        }
        
        selectedTicketType = type;
        updateDisplay("已选择 " + selectedTicketType + "，请选择座席类型。");
    }
    
    /**
     * 选择座席类型
     */
    private void selectCategory(String category) {
        if (!isDestSelected) {
            updateDisplay("请先选择目的地！");
            return;
        }
        
        if (selectedTicketType.isEmpty()) {
            updateDisplay("请先选择车票类型！");
            return;
        }
        
        selectedCategory = category;
        totalAmount = ticketService.calculateTotal(selectedTicketType, selectedCategory, ticketQuantity);
        
        if (totalAmount <= 0) {
            updateDisplay("无效的票价组合，请重新选择！");
            return;
        }
        
        isTicketTypeSelected = true;
        updateDisplay("已选择 " + selectedTicketType + "-" + selectedCategory + 
                "，价格：¥" + totalAmount + "\n请点击继续或取消。");
    }
    
    /**
     * 处理支付
     */
    private void processPayment(String method) {
        if (!isTicketTypeSelected || !isDestSelected) {
            updateDisplay("请先完成选择！");
            return;
        }
        
        // 创建交易记录
        com.tss.model.TransactionRecord record = new com.tss.model.TransactionRecord();
        record.setDestCode(destinationCode);
        record.setTicketType(selectedTicketType + "-" + selectedCategory);
        record.setAmount(totalAmount);
        record.setPaymentMethod(method);
        
        // 完成交易
        boolean success = ticketService.completeTransaction(record);
        
        if (success) {
            updateDisplay("支付成功！车票已打印，交易完成。\n" +
                    "车票信息：\n" +
                    "目的地代码：" + destinationCode + "\n" +
                    "车票类型：" + selectedTicketType + "-" + selectedCategory + "\n" +
                    "价格：¥" + totalAmount + "\n" +
                    "支付方式：" + method);
            
            // 重置选择
            resetAllSelections();
        } else {
            updateDisplay("支付失败，请重试！");
        }
    }
    
    /**
     * 重置所有选择
     */
    private void resetAllSelections() {
        destinationCode = "";
        selectedTicketType = "";
        selectedCategory = "";
        totalAmount = 0.0;
        isDestSelected = false;
        isTicketTypeSelected = false;
        updateDisplay("已重置，请选择目的地。");
    }
    
    /**
     * 主方法
     */
    public static void main(String[] args) {
        // 使用系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 启动应用
        SwingUtilities.invokeLater(() -> {
            MainFrame frame = new MainFrame();
            frame.setVisible(true);
        });
    }
} 